﻿#region Imports
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using CommonUtilities.Extensions;
using ListCreator.Properties;
using System.Configuration;
#endregion Imports

namespace ListCreator
{
    public partial class frmListCreator : Form
    {
        string namelist_final = "";
        Dictionary<string, string> dictNames = new Dictionary<string, string>();
        private bool isCreateListRunning = false;
        ListProcessingEventArgs listProcessingEventArgs;
        private DateTime startTime;
        string lastConvertedData = "";

        public frmListCreator()
        {
            InitializeComponent();

            tmrClipboardChecker.Start();

            txtHint.Text = Resources.ListCreator_Hint.FormatTextFromParams(ConfigurationManager.AppSettings["DefaultPrefix"], ConfigurationManager.AppSettings["AlternatePrefix"]);
            txtInstructions.Text = Resources.ListCreator_Instructions;

            txtNames.Focus();
            //if (!Debugger.IsAttached) txtNames.Text = "";
            lstNames_SizeChanged(null, null);
            btnCopyConverted.Enabled = false;
            RemoveDupes();
        }

        private void RemoveDupes()
        {
            txtNames.Lines = txtNames.Lines.Distinct().ToArray();
        }

        private void lstNames_SizeChanged(object sender, EventArgs e)
        {
            dgvNames.Height = txtNames.Height;
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            namelist_final = "";

            dictNames = txtNames.Lines.Where(nm => !String.IsNullOrEmpty(nm)).ToDictionary(d => d, d => d);
            dictNames.Where(nm => nm.Key.Contains(",")).ToList().ForEach(nm =>
            {
                dictNames[nm.Key] = String.Format("{0} {1}", nm.Key.Split(',').Last().Trim(), nm.Key.Split(',').First().Trim()).Trim();
            });

            dgvNames.DataSource = dictNames.Select(nm => new { Org = nm.Key, Formatted = nm.Value, Conv = (nm.Key != nm.Value) ? "Y" : "" }).ToList();
        }

        private void btnCopyClipboard_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(namelist_final)) CreateNameList(dictNames.Values);
            if (!String.IsNullOrEmpty(namelist_final)) Clipboard.SetText(namelist_final);
        }

        private void txtNames_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A) txtNames.SelectAll();
        }

        public void CreateNameList(IEnumerable<string> namelist)
        {
            bool started = false;
            dictNames = namelist.Where(nm => !String.IsNullOrEmpty(nm)).ToDictionary(d => d, d => d);

            dictNames.ToList().ForEach(nm =>
            {
                if (nm.Key.Contains(",")) dictNames[nm.Key] = String.Format("{0} {1}", nm.Key.Split(',').Last().Trim(), nm.Key.Split(',').First().Trim());
                namelist_final += (started ? Environment.NewLine : "") + nm.Value;
                started = true;
            });
        }

        private void btnCreateList_Click(object sender, EventArgs e)
        {
            startTime = DateTime.Now;
            listProcessingEventArgs = new ListProcessingEventArgs();
            listProcessingEventArgs.RecordCount = GenerateCount();
            lblProcessingStatus.Text = String.Format("Records to process : {0}", listProcessingEventArgs.RecordCount);

            //ProcessStartInfo processStartInfo = new ProcessStartInfo();
            //processStartInfo.FileName = (Debugger.IsAttached ? @"C:\Users\D7729377\Documents\Visual Studio 2010\Projects\CreateList\CreateList\bin\Release\" : "") + "CreateList.exe";

            tmrProcessChecker.Start();
            btnCreateList.Enabled = false;
            btnCopyConverted.Enabled = false;

            try
            {
                if (chkModifierAlt.Checked) chkModifierAlt.ForeColor = Color.Blue;
                if (chkModifierCtrl.Checked) chkModifierCtrl.ForeColor = Color.Blue;

                //Process process = Process.Start(processStartInfo);
                isCreateListRunning = true;
                ListProcessingEventArgs.ProcessedCountChanged += new EventHandler(UpdateProcessedCount);

                RunForrestRun();
            }
            catch (Exception)
            {
                btnCreateList.Enabled = true;
                btnCopyConverted.Enabled = true;
                UpdateStatus();
            }
        }

        private void RunForrestRun()
        {
            new ListCreator().frmCreateList_Load(null, listProcessingEventArgs);

            lastConvertedData = Clipboard.GetText();
            tltipMain.SetToolTip(btnCopyConverted, GeneratePartText());

            isCreateListRunning = false;
        }

        private void UpdateProcessedCount(object sender, EventArgs e)
        {
            UpdateStatus();
        }

        private void UpdateStatus()
        {
            lblProcessingStatus.Text = String.Format("Records processed : {0} / {1} ( {2} % )", listProcessingEventArgs.ProcessedCount, listProcessingEventArgs.RecordCount, GerPercentage(listProcessingEventArgs));
            lblTimeElapsed.Text = String.Format("Started: {0}        Elapsed: {1}", startTime.ToString("dd-MMM HH:mm:ss"), (DateTime.Now - startTime).ToString().Substring(3, 9));
            progStatus.Value = GerPercentage(listProcessingEventArgs);

            //Action secondFooAsync = new Action(SecondFoo);
            //secondFooAsync.BeginInvoke(new AsyncCallback(result =>
            //{
            //    (result.AsyncState as Action).EndInvoke(result);
            //}), secondFooAsync); 

            this.Refresh();
        }

        private int GerPercentage(ListProcessingEventArgs listProcessingEventArgs)
        {
            return (int)((double)listProcessingEventArgs.ProcessedCount / (double)listProcessingEventArgs.RecordCount * 100);
        }

        private int GenerateCount()
        {
            TextBox tmp = new TextBox { Text = Clipboard.GetText() };
            return tmp.Lines.Count();
        }

        private void tmrProcessChecker_Tick(object sender, EventArgs e)
        {
            if (Process.GetProcessesByName("CreateList").Count() == 0 && !isCreateListRunning)
            {
                tmrProcessChecker.Stop();
                chkModifierAlt.ForeColor = chkModifierCtrl.ForeColor = Color.Black;

                if (MessageBox.Show("Format for CRM view\n(creates items delimited by semicolon)?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    Clipboard.SetText(Clipboard.GetText().Replace("', '", ";").Replace("''", "'").Trim("(' )".ToCharArray()));

                btnCreateList.Enabled = true;
                btnCopyConverted.Enabled = true;
            }
        }

        private void tmrClipboardChecker_Tick(object sender, EventArgs e)
        {
            try
            {
                txtClipboardData.Text = Clipboard.GetText();
                btnCreateList.Enabled = !String.IsNullOrEmpty(txtClipboardData.Text);

                chkModifierCtrl.Checked = (Form.ModifierKeys == Keys.Control);
                chkModifierAlt.Checked = (Form.ModifierKeys == Keys.Alt);
            }
            catch (Exception) { }
        }

        private void btnCopyConverted_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Copy previously converted text to clipboard?\n\n" + GeneratePartText(), "Confirmation..", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                Clipboard.SetText(lastConvertedData);
        }

        private string GeneratePartText()
        {
            return lastConvertedData.Length > 200 ? lastConvertedData.Substring(0, 200) + ".." : lastConvertedData;
        }
    }
}
